﻿/*
 * ======================================================================
 *                           Modern Warfare3 Launcher
 * Copyright 2011-2012
 * Developer:Pooya parsa
 * Email:pingsft@gmail.com
 * You are ALLOWED:
 * -Read source code
 * -Use some part of source code with Full name and email of developer
 * -Release your own mod with name of develepor
 * You are NOT ALLOWD:
 * -Add cracked version of Mw3
 * -Release modified version as MW3Launcher
 * -Mirror Sourcecode
 * -Use source code without name of developer
 * Thank you for your attention
 * ======================================================================
 * */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;

namespace MW3Launcher
{
    public partial class Settings : Form
    {

        private string steamid;
        private glass_helper AeroG;
        window_mover mover;
        public Settings()
        {
            try
            {
                InitializeComponent();
                AeroG = new glass_helper(this);
                mover = new window_mover(this);
                this.Load += new EventHandler(Settings_Load);
                try
                {
                    txtName.Text = Environment.UserName;
                    txtExternalIp.Text = GetlanIp();
                }
                catch
                {
                }
                this.txtName.Focus();
                try
                {
                    if (File.Exists("teknogods.ini") && File.Exists("Mw3 Launcher.ini"))
                    {
                        IniParser parser = new IniParser("teknogods.ini");
                        IniParser parser2 = new IniParser("Mw3 Launcher.ini");


                        try
                        {
                            this.txtName.Text = parser.GetSetting("Settings", "Name");
                            this.steamid = parser.GetSetting("Settings", "ID");
                            this.txtFov.Text = parser.GetSetting("Settings", "FOV");
                            string ei = parser.GetSetting("Network", "ExternalIP");
                            if (ei != null && ei != String.Empty)
                            {
                                txtExternalIp.Text = ei;
                                chExternalIp.Checked = true;
                                chExternalIp_CheckedChanged(null, null);
                            }
                        }
                        catch { }
                        try
                        {
                            chOffline.Checked = (parser2.GetSetting("Network", "Offline") == "1");
                        }
                        catch { }
                        try
                        {
                            int num = Convert.ToInt32(this.txtFov.Text);
                            if ((num > 90) || (num < 10))
                                this.txtFov.Text = "65";
                            else
                                this.txtFov.Text = num.ToString();
                        }
                        catch (Exception)
                        { this.txtFov.Text = "65"; }
                    }
                    else
                    {
                        string[] files = Directory.GetFiles(@".\players2\", "*.stat");
                        for (int i = 0; i < files.Length; i++)
                        {
                            files[i] = files[i].Replace(@".\players2\", string.Empty);
                        }
                        List<string> list = new List<string>();
                        for (int j = 0; j < files.Length; j++)
                        {
                            if (files[j].StartsWith("iw5"))
                            {
                                string[] strArray2 = files[j].Split("_".ToCharArray());
                                if (strArray2.Length == 5)
                                {
                                    list.Add(strArray2[4].Substring(7, 8));
                                }
                            }
                        }
                        if (list.Count >= 1)
                        {
                            foreach (KeyValuePair<string, int> pair in (from x in list group x by x).ToDictionary<IGrouping<string, string>, string, int>(g => g.Key, g => g.Count<string>()))
                            {
                                this.steamid = pair.Key;
                                return;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    File.Delete("teknogods.ini");
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("Unable to load Settings: "+ee.Message, "Error");
            }
        }

        void Settings_Load(object sender, EventArgs e)
        {
            AeroG.applyAeroGlass(0,0,pnl.Top,Height-pnl.Bottom-18);
            mover.make_movable(aeroLable1);
            mover.make_movable(pictureBox1);
            mover.make_movable_all();

        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool fill_error = false;
                string IPMatchExp = @"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})";
                string Eip = "";
                //Error checking
                   if (this.txtName.Text=="")
                   { MessageBox.Show("Please first set nickname", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); fill_error = true; return; }
                if (chExternalIp.Checked && !Regex.Match(txtExternalIp.Text, IPMatchExp).Success)
                { MessageBox.Show("External ip is not in correct format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); fill_error = true; return; }
                else if (chExternalIp.Checked)
                {
                    try
                    {
                        Eip = CurrectIp(txtExternalIp.Text);
                    }
                    catch
                    {
                        chExternalIp.Checked = false;
                    }
                }

                if (!fill_error)
                {
                    IniParser b = new IniParser("Mw3 Launcher.ini");
                    IniParser a = new IniParser("teknogods.ini");
                    //Name
                    a.AddSetting("Settings", "Name", this.txtName.Text);
                    //Steam id
                    if (!(this.steamid==null || this.steamid.Replace(" ","")=="") && (this.steamid != "00010000"))
                        a.AddSetting("Settings", "ID", this.steamid);
                    else
                        a.DeleteSetting("Settings", "ID");
                    //FOV
                    a.AddSetting("Settings", "FOV", this.txtFov.Text);
                    //External ip
                    if (chExternalIp.Checked)
                        a.AddSetting("Network", "ExternalIP", Eip);
                    else
                        a.DeleteSetting("Network", "ExternalIP");
                    //Offline
                    b.AddSetting("Network", "Offline", chOffline.Checked ? "1" : "0");
                    //Save settings
                    a.SaveSettings();
                    b.SaveSettings();
                    //Restart app
                    this.Close();
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show("Unable to save Settings: " + ee.Message, "Error");
            }
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void chExternalIp_CheckedChanged(object sender, EventArgs e)
        {
            txtExternalIp.Enabled =btnUseMyIp.Enabled= chExternalIp.Checked;
        }

        string CurrectIp(string ip)
        {
            string r="";
            foreach (string s in ip.Split('.'))
                r += String.Format("{0:000}.", Convert.ToInt16(s));
            r=r.Remove(r.Length-1);
            return r;
        }

        string GetlanIp()
        {
            try
            {
                IPAddress[] ips = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
                foreach (IPAddress ip in ips)
                {
                    if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        return ip.ToString();
                }
            }
            catch { }
            return "";
        }

        private void btnUseMyIp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtExternalIp.Text = GetlanIp();
        }

        private void chOffline_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}
